import { Card, Button, Checkbox, Form, Input, message } from 'antd'
import { useDispatch } from 'react-redux'

import logo from '@/assets/logo.png'
import './index.scss'
import { loginAction } from '@/store/actions/login'
import { useLocation, useNavigate } from 'react-router-dom'

const Login = () => {
  const dis = useDispatch()
  const nav = useNavigate()
  const location = useLocation()
  console.log('location', location)
  /**
   * 表单校验通过后执行
   * @param {*} formData 表单变量的值
   */
  const onFinish = async (formData) => {
    console.log('formData数据：', formData)
    try {
      // 分发异步action
      await dis(loginAction(formData))
      message.success('登录成功')
      // 跳转页面
      nav(location.state?.redirectUrl || '/')
      // console.log(111, location.state?.redirectUrl)
      // nav('/')
    } catch (error) {
      console.log(error)
      message.error(error.response.data.message)
    }
  }

  // 校验选择框是否勾选
  // (_, value) =>
  //       value
  //        ? Promise.resolve()
  //        : Promise.reject(new Error('Should accept agreement'))
  /**
   *
   * @param {*} rule 校验规则
   * @param {*} value 校验表单项的值=>checkbox的值：true选中 | false 未选中
   * 1. true 选中 => 校验通过 => Promise.resolve()
   * 2. false 未选中 =》校验不通过 =》Promise.reject(new Error('错误提示的message'))
   */
  const validCode = (rule, value) => {
    if (!value) {
      return Promise.reject(new Error('请同意用户协议！'))
    }
    return Promise.resolve()
  }

  return (
    <div className="login">
      <Card className="login-container">
        <img className="login-logo" src={logo} alt="" />
        {/* 登录表单 */}
        <Form
          // 表单变量初始化值
          validateTrigger={['onBlur', 'onChange']}
          initialValues={{
            // 测试账号
            mobile: '13911111111',
            code: '246810',
            agree: true,
          }}
          onFinish={onFinish}
          autoComplete="off">
          {/*1. 手机号 */}
          <Form.Item
            // name定义表单变量名叫啥
            name="mobile"
            // rules指定校验规则
            rules={[
              {
                pattern:
                  /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
                message: '手机号码格式不对!',
                validateTrigger: 'onBlur',
              },
              { required: true, message: '请输入手机号！' },
            ]}>
            <Input placeholder="请输入手机号" />
          </Form.Item>
          {/*2. 验证码 */}
          <Form.Item
            name="code"
            rules={[
              { len: 6, message: '验证码6个字符', validateTrigger: 'onBlur' },
              { required: true, message: '请输入验证码!' },
            ]}>
            <Input.Password placeholder="请输入验证码" />
          </Form.Item>
          {/*3. 使用协议 */}
          <Form.Item
            name="agree"
            rules={[
              {
                // 提供校验函数
                validator: validCode,
              },
            ]}
            valuePropName="checked">
            <Checkbox>我已阅读并同意[用户协议] 和 [隐私条款]</Checkbox>
          </Form.Item>
          {/* 4. 登录按钮 =>htmlType="submit" 指定作为 */}
          <Form.Item>
            <Button block size="large" type="primary" htmlType="submit">
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default Login
